package com.sopaths.utility.rmi;

import java.util.HashMap;
import java.util.Map;

import org.springframework.remoting.rmi.RmiProxyFactoryBean;

import com.sopaths.contract.rmi.ServerInfo;

public class SopathsRmiProxyFactory {

	private static Map<String, Object> proxies = new HashMap<>();

	@SuppressWarnings("unchecked")
	public static <T> T createProxy(ServerInfo server, String serviceName, Class<T> clazz) {
		String url = "rmi://" + server.getHost() + ":" + server.getPort() + "/" + serviceName;
		synchronized (proxies) {
			if (!proxies.containsKey(url)){
				RmiProxyFactoryBean factory = new RmiProxyFactoryBean();
				factory.setServiceUrl("rmi://" + server.getHost() + ":" + server.getPort() + "/" + serviceName);
				factory.setServiceInterface(clazz);
				factory.afterPropertiesSet();
				proxies.put(url, factory.getObject());
			}
		}
		return (T) proxies.get(url);
	}
}
